package com.second.tictactoeandroid2;

import com.example.tictactoeandroid.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View; 
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;  
import io.GUIInputOutput;
import io.InputOutput;
import game.Engine; 
import java.io.IOException; 
 

public class GameBoardActivity extends Activity {
	
	private Engine engine = new Engine(); 
	private GameThread gameThread = new GameThread(); 
	private Thread engineThread = new Thread(gameThread); 
	private InputOutput gui = new GUIInputOutput(this); 
	
	public static String USER_NAME =  "com.second.tictactoeandroid2.username"; 
	public static String SCORE = "com.second.tictactoeandroid2.score";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_board);
		Intent intent = getIntent(); 
		String name = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
		System.out.println("name" + name); 
		TextView text = (TextView)findViewById(R.id.userNameInput); 
		System.out.println("text" + text); 
		text.setText(name); 
		engineThread.start(); 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.game_board, menu);
		return true;
	}
	
	public void setMove(View view) throws IOException{
	//	Button myButton = (Button)view; 
	/*	String buttonText = "X"; 
		myButton.setText(buttonText); */
		int move = -1; 
		switch(view.getId()){
			case R.id.button1: 
				move = 0; 
				break; 
			case R.id.button2: 
				move = 1; 
				break;
			case R.id.button3:
				move = 2; 
				break; 
			case R.id.button4:
				move = 3; 
				break;
			case R.id.button5:
				move = 4; 
				break; 
			case R.id.button6:
				move = 5; 
				break; 
			case R.id.button7: 
				move = 6; 
				break; 
			case R.id.button8: 
				move = 7; 
				break;
			case R.id.button9:
				move = 8; 
				break;
			default:
				throw new RuntimeException("unknown button id"); 
		}
		gui.passMove(move); 
	}
	
	public void saveHighScores(View view){
		Intent intent = new Intent(this, HighScoreActivity.class); 
		TextView userNameField = (TextView)findViewById(R.id.userNameInput); 
		String userName = userNameField.getText().toString(); 
		int score = gui.getScore(); 
		intent.putExtra(USER_NAME, userName);
		intent.putExtra(SCORE, score);
		startActivity(intent); 
	}
	
	private class GameThread implements Runnable {
		public void run() {
			try{
				engine.playGame(gui); 
			} catch(IOException e) {
				System.out.println("IOException" + e); 
			}
		}
	}
}
